//
//  LQLoginViewController.m
//  LQProductIntelligenceService
//
//  Created by Yim on 16/5/13.
//  Copyright © 2016年 LQ. All rights reserved.
//

#import "LQLoginViewController.h"
#import "LQCompanyViewController.h"
#import "LQKeyChain.h"
#import "LQUserInfo.h"
#import "LQRegisterViewController.h"



@interface LQLoginViewController ()<UITextFieldDelegate>
{
    NSNumber *_userLogin;
    BOOL _EMLogin;
    int _total;
}


@property (nonatomic , strong) LQCompanyViewController *companyView;


// 用户名
@property (weak, nonatomic) IBOutlet UITextField *userNameField;
// 用户密码
@property (weak, nonatomic) IBOutlet UITextField *userPasswordField;
// 点击登录btn
- (IBAction)clickLoginBtn:(UIButton *)sender;
// 点击密码重置btn
- (IBAction)clickPasswordResetBtn:(UIButton *)sender;

// 点击查看密码
- (IBAction)clickLookPasswordBtn:(UIButton *)sender;

//公司名字
@property (nonatomic, copy) NSString *companyName;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIButton *rememberBtn;


- (IBAction)clickChangeRememberStatusBtn:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIView *baseView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;

@property (weak, nonatomic) IBOutlet UIView *remindView;
@property (weak, nonatomic) IBOutlet UILabel *remindLabel;
@property (nonatomic , strong) NSArray *textfieldArray;


@property (nonatomic , strong) NSArray *subArray;

/**  *  所有设备信息数组    */
@property (nonatomic , strong) NSMutableArray *devices;

@end

@implementation LQLoginViewController
// 初始化选择公司视图
- (LQCompanyViewController *)companyView
{
    if (!_companyView) {
        _companyView = [[LQCompanyViewController alloc] init];
    }
    return _companyView;
}

/**
 *  搜索设备信息用
 */
- (NSMutableArray *)devices
{
    if (!_devices) {
        _devices = [NSMutableArray array];
    }
    return _devices;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    /**
     *  更新cookie
     */
//    [[LQUserInfo sharedLQUserInfo] updateSession];
    _EMLogin = NO;
 
    
   
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([_userLogin intValue]) {
        //        [self loginSuceess];
    }
}
/**
 *  增加辅助键盘
 */


- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
    [self settingsFieldLeftView];
    self.rememberBtn.selected = YES;
    NSMutableDictionary *dict = [LQKeyChain load:@"userInfo"];
    MYLog(@"userInfo = %@",dict);
    if (dict != nil) {
        self.userNameField.text = dict[@"username"];
        
        //判断是否Wie修改密码返回的数据，如果是，则去除密码和保存密码的按钮
        if (![self.userPasswordField.text isEqualToString:@" "]) {
            self.userPasswordField.text = dict[@"password"];
            self.rememberBtn.selected = YES;
        }
        else
        {
            self.userPasswordField.text = nil;;
            self.rememberBtn.selected = NO;
        }
    }
    
}


- (void) settingsFieldLeftView
{
    // 给Filed设置左边视图
    UIImage *imageN = [UIImage imageNamed:@"icon"];
    UIImageView *leftVN = [[UIImageView alloc]initWithImage:imageN];
    leftVN.contentMode = UIViewContentModeCenter;
    leftVN.frame = CGRectMake(0, 0, 50, 20);
    self.userNameField.leftViewMode = UITextFieldViewModeAlways;
    self.userNameField.leftView = leftVN;
    
    UIImage *imageP = [UIImage imageNamed:@"lock"];
    UIImageView *leftVP = [[UIImageView alloc]initWithImage:imageP];
    leftVP.contentMode = UIViewContentModeCenter;
    leftVP.frame = CGRectMake(0, 0, 50, 20);
    self.userPasswordField.leftViewMode = UITextFieldViewModeAlways;
    self.userPasswordField.leftView = leftVP;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.userNameField) {
        
        [self.userPasswordField becomeFirstResponder];
        
    }else if (textField == self.userPasswordField)
    {
        [self.view endEditing:YES];
        [self clickLoginBtn:nil];
    }
    return YES;
}




#pragma mark - 和网络相关


//- (void) sendRequsetToServer
//{
//    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    dic[@"userName"] = self.userNameField.text;
//    dic[@"password"] = self.userPasswordField.text;
//    [LQHTTPTool POST:loginUrl params:dic success:^(id json) {
//        MYLog(@"登录成功 = %@",json);
//        NSString *msg = json[@"msg"];
//        _userLogin = json[@"success"];
//        if ([_userLogin intValue]) {
//            
//            /**
//             *  先移除上次的cookie
//             */
//            [[LQUserInfo sharedLQUserInfo] removeLoginSession];
//            /**
//             *  获取cookie
//             */
//            
//            [[LQUserInfo sharedLQUserInfo] getAndSaveLoginSession];
//            /**
//             *  保存用户名和密码
//             */
//            [LQUserInfo sharedLQUserInfo].userName = self.userNameField.text;
//            [LQUserInfo sharedLQUserInfo].password = self.userPasswordField.text;
//            
//            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//            [dict setObject:self.userNameField.text forKey:@"username"];
//            [self saveProfile];
//            /**
//             *  环信登录
//             */
//            [self EMSDKLogin];
//            
//            
//            /**
//             *  加载用户类型信息
//             */
//            [self loadUserInfo];
//            
//        }else
//        {
//            [SVProgressHUD dismiss];
//            self.loginBtn.enabled = YES;
//            self.remindLabel.text = msg;
//            [self popupRemindView];
//        }
//        
//    } failure:^(NSError *error) {
//        self.loginBtn.enabled = YES;
//        MYLog(@"登录请求失败:%@",error);
//        [SVProgressHUD showErrorWithStatus:@"登录失败!" withDuration:1.5f];
//        
//    }];
// 
//
//}








- (IBAction)clickLoginBtn:(UIButton *)sender {
    self.loginBtn.selected = !self.loginBtn.selected;
    if ((self.userNameField.text.length <= 0) || (self.userPasswordField.text.length <= 0)) {
        self.remindLabel.text = @"用户名或密码不能为空";
        [self popupRemindView];
        return ;
    }
    
    
    self.loginBtn.enabled = NO;
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [SVProgressHUD dismiss];
//        self.loginBtn.enabled = YES;
//    });
    // 发送请求到服务器
    
    
}




/**
 *  用户名或密码错误抖动动画 */

- (void) setupShakeAnimation
{
    if (self.loginBtn.selected) {
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.0 initialSpringVelocity:5.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGPoint point = self.baseView.center;
            point.x += 3;
            [self.baseView setCenter:point];
        } completion:nil];
        [self recoverRemindView];
    }else
    {
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.0 initialSpringVelocity:5.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGPoint point = self.baseView.center;
            point.x -= 3;
            [self.baseView setCenter:point];
        } completion:nil];
        [self recoverRemindView];
    }
}
/**
 *  弹出提示View
 */
- (void) popupRemindView
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.remindView.hidden = NO;
            CGFloat distance =  120;
            self.topConstraint.constant = distance;
            [UIView animateWithDuration:0.1 animations:^{
                [self.view layoutIfNeeded];
            }];
            // 动画抖动
            [self setupShakeAnimation];
        });
    });
}
/**
 *  收回View
 */
- (void) recoverRemindView
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.remindView.hidden = YES;
                CGFloat distance =  50;
                self.topConstraint.constant = distance;
                [UIView animateWithDuration:0.1 animations:^{
                    [self.view layoutIfNeeded];
                }];
            });
        });
    });
}
- (IBAction)clickPasswordResetBtn:(UIButton *)sender
{
    
}


- (IBAction)clickLookPasswordBtn:(UIButton *)sender
{
    self.userPasswordField.secureTextEntry = !self.userPasswordField.secureTextEntry;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}






- (IBAction)clickChangeRememberStatusBtn:(UIButton *)sender {
    BOOL flag = !self.rememberBtn.selected;
    self.rememberBtn.selected = flag;
}


#pragma mark - 保存用户名、密码

- (void)saveProfile {
    if (self.rememberBtn.selected) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:self.userNameField.text forKey:@"username"];
        [dict setObject:self.userPasswordField.text forKey:@"password"];
        [LQKeyChain save:@"userInfo" data:dict];
    } else {
        [LQKeyChain remove:@"userInfo"];
    }
}



- (void) dealloc
{
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
   
}
@end
